<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="文档标题" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入文档标题"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="创建者" prop="creator">
          <el-input
            v-model="queryParams.creator"
            placeholder="请输入创建者"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="文档状态" clearable style="width: 200px">
            <el-option label="已发布" value="PUBLISHED" />
            <el-option label="草稿" value="DRAFT" />
            <el-option label="归档" value="ARCHIVED" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 文档表格 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="documentList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="文档标题" align="center" prop="title" :show-overflow-tooltip="true" />
        <el-table-column label="创建者" align="center" prop="creatorName" width="120" />
        <el-table-column label="分类" align="center" prop="categoryName" width="100" />
        <el-table-column label="版本" align="center" prop="version" width="80" />
        <el-table-column label="协作者数量" align="center" prop="collaboratorCount" width="100" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="最后编辑" align="center" prop="updateTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template #default="scope">
            <div class="table-operation-wrapper">
              <el-button
                type="primary"
                icon="View"
                @click="handleView(scope.row)"
                class="table-operation-button is-primary"
                size="small"
              >查看</el-button>
              <el-button
                type="danger"
                icon="Delete"
                @click="handleDelete(scope.row)"
                class="table-operation-button is-danger"
                size="small"
              >删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDocumentPage, deleteDocument } from '@/api/document'
import { useRouter } from 'vue-router'
import Pagination from '@/components/Pagination/index.vue'

const router = useRouter()

// 响应式数据
const loading = ref(true)
const ids = ref([])
const total = ref(0)
const documentList = ref([])
const queryFormRef = ref()

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  title: undefined,
  creator: undefined,
  status: undefined
})

// 获取文档列表
const getList = async () => {
  loading.value = true
  try {
    const response = await getDocumentPage(queryParams)
    if (response.code === 200) {
      documentList.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取文档列表失败')
    }
  } catch (error) {
    console.error('获取文档列表失败:', error)
    ElMessage.error('获取文档列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
}

// 查看文档
const handleView = (row) => {
  router.push(`/document/document/${row.id}/view`)
}

// 删除按钮操作
const handleDelete = (row) => {
  const documentIds = row.id ? [row.id] : ids.value
  ElMessageBox.confirm('是否确认删除文档编号为"' + documentIds + '"的数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDocument(documentIds[0])
      getList()
      ElMessage.success('删除成功')
    } catch (error) {
      console.error('删除文档失败:', error)
      ElMessage.error('删除文档失败')
    }
  }).catch(() => {})
}

// 工具函数
const getStatusType = (status) => {
  const typeMap = {
    'PUBLISHED': 'success',
    'DRAFT': 'warning',
    'ARCHIVED': 'info'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    'PUBLISHED': '已发布',
    'DRAFT': '草稿',
    'ARCHIVED': '归档'
  }
  return textMap[status] || status
}

// 时间格式化
const parseTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString()
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.search-card {
  margin-bottom: 16px;
}
</style>
